<template>
  <basic-container>

    <template>
      <div class="form-designer">
        <el-container style="border: #e0e0e0 solid 1px;">
          <el-aside width="240px">
            <el-header style="z-index:100;border-right: 1px solid #e0e0e0;border-bottom: 1px solid #e0e0e0;height:50px;text-align: center;line-height: 50px;width:240px;position: absolute;background: #fff">工艺</el-header>
            <div style="height:800px;margin-top:45px">
              <!--工艺菜单-->
              <craftMenu/>
            </div>
          </el-aside>
          <el-main class="demo" style="outline: 1px solid #e0e0e0;">
            <div style="background:#fff;height: 50px;border-bottom: 1px solid #e0e0e0;line-height: 50px;padding-left:5px ">
              <!-- 品号：<avue-input v-model="articleNumber" style="width:140px;margin-right: 5px" placeholder="请输入品号" ></avue-input>-->
              产品类型：<el-select v-model="productLineType" placeholder="请选择产品类型"  filterable clearable style="width:200px;margin-right: 5px">
              <el-option
                v-for="item in productLineTypeList"
                :key="item.label"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
              工艺模板名称：<avue-input v-model="craftLineName" style="width:180px;margin-right: 5px" placeholder="请输入工艺模板名称" ></avue-input>
              流程图号：<avue-input v-model="flowChartNo" style="width:180px;margin-right: 5px" placeholder="请输入流程图号" ></avue-input>
              <el-button type="primary" @click="saveLine">保存</el-button>
            </div>
            <avue-flow :height="800"
                       width="100%"
                       style="min-height: 800px;"
                       ref="flow"
                       :option="option"
                       v-model="flowForm">
              <template #header="{node}" >
                {{(node || {}).name}}
                <i class="el-icon-delete"  style="float: right;line-height: 30px;margin-right: 2px" @click="deleteNode(node)"></i>
              </template>
              <template slot-scope="{node}">
                <span style="height: 40px;line-height: 40px;">{{(node || {}).name}}</span>
              </template>
            </avue-flow>

          </el-main>
        </el-container>
      </div>
    </template>
    <template>
    </template>
  </basic-container>
</template>

<script>
import {saveCraftProdict } from '@/api/pfoc/craftproduct'
import craftMenu from '@/views/pfoc/craft/craft-menu'

export default {
  name: "craft",
  components: {
    craftMenu,
  },
  props:{
    productLineTypeList:{//产线类型集合
      type:Array
    }
  },
  provide() {
    return {
      craftAddThis: this
    }
  },
  data() {
    return {
      count: 0,
      nodeCount:0,//节点下标
      form: [],//提交时数据集合
      coveringJson:[],//节点删除后补位集合
      flowForm:'',
      craftLineName:null,//工艺产线名称
      productLineType:null,//产线类型
      flowChartNo:null,//流程图号
      option: {
        name: null,
        nodeList: [],//工艺节点集合
        lineList: [],//工艺各节点指向顺序集合
      }
    };
  },
  created() {
  },
  computed: {
    nodeList () {
      return this.option.nodeList
    }
  },
  mounted() {
    this.nodeCount = this.option.nodeList.length;//初始化节点下标
  },
  methods: {
    /**添加工艺*/
    addCraftNode(name,id){//工艺名称，工艺ID
      if (this.coveringJson.length > 0) {
        // 提醒是否按顺序补位
        this.$confirm('是否按顺序补位?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.addNodeFromCoveringJson(name, id);
        }).catch(() => {
          this.addNodeManually(name, id);
        });
      } else {
        this.addNodeManually(name, id);
      }
    },
    addNodeFromCoveringJson(name, id) {
      // 需要补位，则每次取出补位集合第一个数据进行补位
      const node = this.coveringJson.shift(); // 移除并返回第一个元素
      const nodeId = node.id;
      const nodeIdNum = parseInt(nodeId.replace(/\D/g, ''), 10); // 提取数字并转换为整数
      // 添加节点
      this.$refs.flow.addNode(name, id, nodeIdNum, node.left, node.top);
      // 画线
      this.drawLinesFromPrevious(nodeIdNum);
      this.drawLinesToNext(nodeIdNum);
    },

    addNodeManually(name, id) {
      let left = 0;
      if ((parseInt(this.nodeCount / 4)) % 2 === 0) {
        left = (this.nodeCount % 4) * 300;
      } else {
        left = ((3 - this.nodeCount % 4) * 300);
      }
      const top = parseInt(this.nodeCount / 4) * 100;
      // 添加节点
      this.$refs.flow.addNode(name, id, this.nodeCount, left, top);
      // 画线
      this.drawLinesFromPrevious(this.nodeCount);
      // 更新节点下标
      this.nodeCount += 1;
    },
    drawLinesFromPrevious(nodeIdNum) {
      const t = this;
      // 从上一个节点到当前节点
      if (t.nodeList.length > 1) {
        const from = `node${nodeIdNum - 1}`;
        const to = `node${nodeIdNum}`;
        t.$nextTick(() => t.$refs.flow.drawLines({ from, to }));
      }
    },
    drawLinesToNext(nodeIdNum) {
      const t = this;
      // 从当前节点到下一个节点
      if (t.nodeList.length >= nodeIdNum) {
        const from = `node${nodeIdNum}`;
        const to = `node${nodeIdNum + 1}`;
        t.$nextTick(() => t.$refs.flow.drawLines({ from, to }));
      }
    },
    /**删除工艺*/
    deleteNode(node){
      const id = node.id;
      var t = this;
      this.$confirm("确定要删除节点" + id + "?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: !1
      }).then((function() {
        console.log(node)
        t.$refs.flow.deleteNode(id);
        let coveringNode = { ...node }
        t.coveringJson.push(coveringNode);
        //补位集合中的数据顺序按照nodeId重新排序
        t.coveringJson.sort((a, b) => parseInt(a.id.replace(/\D/g, ''), 10) - parseInt(b.id.replace(/\D/g, ''), 10));
      })).catch((function() {}))
    },
    /**保存工艺产线*/
    saveLine(){
      if(this.validatenull(this.productLineType)){
        this.$message.warning("产品类型不能为空。")
        return;
      }
      if(this.validatenull(this.craftLineName)){
        this.$message.warning("工艺模板名称不能为空。")
        return;
      }
      if(this.validatenull(this.flowChartNo)){
        this.$message.warning("流程图号不能为空。")
        return;
      }
      if(this.validatenull(this.option.nodeList)){
        this.$message.warning("请选择工艺作业步骤创建工艺。")
        return;
      }
      //组装需要提交的数据-工艺主表数据组装
      var params = {};//主表参数集合
      params.craftLineName = this.craftLineName;//工艺产线名称
      params.productLineType = this.productLineType;//产线类型名称
      params.flowChartNo = this.flowChartNo;//流程图号
      params.processNodes = JSON.stringify(this.option.nodeList);//工艺节点集合（其中mark字段为工艺ID）
      params.processNodeLine = JSON.stringify(this.option.lineList);//工艺各节点指向顺序集合
      params.coveringJson = JSON.stringify(this.coveringJson);//节点补位集合
      //提交
      saveCraftProdict(params).then(response => {
        this.$message.success("保存成功。")
        this.$emit('closeAddCraft');//关闭新增页面
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      });
    },
  }
};
</script>

<style scoped>
/deep/.avue-flow__node{
  height: auto!important;
}
/deep/ .avue-flow__node-header {
  line-height: 30px;
}
/deep/.el-descriptions__title {
  font-size: 14px;
  font-weight: 400;
  margin-top: 5px;
}

/*以下样式是打印的时候avue表格错乱修正方式（主要是序号列和操作列固定影响的）*/
/deep/.el-table__fixed{
  display: none!important;
}
/deep/.el-table__fixed-right{
  display: none!important;
}
/deep/.el-table__cell.is-hidden>*{visibility:visible !important;}

/deep/ .avue-grid{
  display: none!important;
}
/deep/.el-main{
  background:#fff !important;
}
/deep/.el-card__body{
  padding: 0px!important;
}
/*去掉滚动条样式*/
.demo::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}
.demo {
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
